package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.sharedmobility.dao.TripDAO;
import com.sharedmobility.dao.VehicleDAO;
import com.sharedmobility.model.Trip;
import com.sharedmobility.model.Vehicle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/trips/*")
public class TripServlet extends HttpServlet {
    private TripDAO tripDAO = new TripDAO();
    private VehicleDAO vehicleDAO = new VehicleDAO();
    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
        
        try {
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                sendErrorResponse(response, "用户未登录");
                return;
            }
            
            if ("/history".equals(pathInfo)) {
                // 获取用户的行程历史
                handleTripHistory(request, response, userId);
            } else if ("/unpaid".equals(pathInfo)) {
                // 获取用户未支付的行程
                handleUnpaidTrips(request, response, userId);
            } else if (pathInfo == null || pathInfo.equals("/")) {
                // 获取用户的所有行程
                handleAllTrips(request, response, userId);
            } else {
                // 获取特定行程详情
                handleTripDetail(request, response, userId, pathInfo.substring(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendErrorResponse(response, e.getMessage());
        }
    }
    
    private void handleAllTrips(HttpServletRequest request, HttpServletResponse response, Integer userId) 
            throws IOException, SQLException {
        List<Trip> trips = tripDAO.findByUserId(userId);
        enrichTripsWithVehicles(trips);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", trips);
        
        response.getWriter().write(gson.toJson(result));
    }
    
    private void handleTripHistory(HttpServletRequest request, HttpServletResponse response, Integer userId) 
            throws IOException, SQLException {
        List<Trip> trips = tripDAO.findByUserId(userId);
        enrichTripsWithVehicles(trips);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", trips);
        
        response.getWriter().write(gson.toJson(result));
    }
    
    private void handleUnpaidTrips(HttpServletRequest request, HttpServletResponse response, Integer userId) 
            throws IOException, SQLException {
        List<Trip> trips = tripDAO.findUnpaidByUserId(userId);
        enrichTripsWithVehicles(trips);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", trips);
        
        response.getWriter().write(gson.toJson(result));
    }
    
    private void handleTripDetail(HttpServletRequest request, HttpServletResponse response, Integer userId, String tripId) 
            throws IOException, SQLException {
        try {
            Integer id = Integer.parseInt(tripId);
            Trip trip = tripDAO.findById(id);
            
            if (trip == null) {
                sendErrorResponse(response, "行程不存在");
                return;
            }
            
            if (!trip.getUserId().equals(userId)) {
                sendErrorResponse(response, "您无权查看此行程");
                return;
            }
            
            // 获取车辆信息
            Vehicle vehicle = vehicleDAO.findById(trip.getVehicleId());
            trip.setVehicle(vehicle);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", trip);
            
            response.getWriter().write(gson.toJson(result));
        } catch (NumberFormatException e) {
            sendErrorResponse(response, "无效的行程ID");
        }
    }
    
    private void enrichTripsWithVehicles(List<Trip> trips) throws SQLException {
        for (Trip trip : trips) {
            Vehicle vehicle = vehicleDAO.findById(trip.getVehicleId());
            trip.setVehicle(vehicle);
        }
    }
    
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        
        response.getWriter().write(gson.toJson(result));
    }
} 